package org.timeticker.impl;

import junit.framework.TestCase;
import org.timeticker.*;
import org.timeticker.impl.ActivityImpl;
import org.timeticker.impl.ActivityListImpl;
import org.timeticker.impl.FSPersistenceImpl;

import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * FSPersistenceImpl Unit Test
 *
 * @author Ivan Latysh
 * @version 0.1
 * @since 16-Jul-2007 : 8:23:18 PM
 */
public class FSPersistenceImplUTest extends TestCase {

  SimpleDateFormat activityKeyFormat = new SimpleDateFormat(Timekeeper.activityKeyDateFormat);

  /**
   * Test saving ActivityListImpl
   */
  public void testSaveLoadActivityList() {
    try {
      // ===================
      // Save Activity List
      // ===================

      Date date = new Date();
      // output file
      File file = new File(System.getProperty("user.dir"), "/activities/"+ FSPersistenceImpl.filenameFormat.format(date)+".xml");
      // activity listImpl
      ActivityListImpl activityList = new ActivityListImpl();
      // add activity
      ActivityImpl activity = new ActivityImpl();
      activity.setTitle("Testing TimeTicker");
      activity.setStartTime(new Date());
      activity.setFinishTime(new Date());
      activityList.add(activity);
      assertEquals(1, activityList.size());
      // save activity
      PersistenceManager.getInstance().persistObjectList(activityKeyFormat.format(date), activityList);
      // check file size
      assertTrue(file.isFile());
      assertTrue(file.length()>100);
      // check serialized data
      String xml = IOHelper.getStringFromReader(new FileReader(file)).toString();
      assertNotNull(xml);
      assertEquals(1, XPathHelper.getInteger(xml, "count(//object[@class='org.timekeeper.impl.ActivityImpl'])").intValue());
      assertEquals("Testing TimeTicker", XPathHelper.getString(xml, "//object[@class='org.timekeeper.impl.ActivityImpl']/void[@property='title']/string"));

      // ===================
      // Load Activity List
      // ===================
      ActivityList activities = (ActivityList) PersistenceManager.getInstance().restoreObjectList(activityKeyFormat.format(date));

      // check result      
      assertNotNull(activities);
      assertEquals(1, activities.size());
      assertEquals("Testing TimeTicker", activities.get(0).getTitle());

    } catch (Exception ex) {
      ex.printStackTrace();
      fail(ex.getMessage());
    }
  }

}
